﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using DynamicChart.Model;
using DynamicChart.Repository;

public class XmlActuatorModelRepository : IActuatorModelRepository
{
    private readonly string _filePath;
    private XDocument _doc;

    public XmlActuatorModelRepository(string filePath)
    {
        _filePath = filePath;
        _doc = XDocument.Load(filePath);
    }

    public IEnumerable<ActuatorModel> GetAll()
    {
        return (from model in _doc.Descendants("ActuatorModel")
                select new ActuatorModel
                {
                    Id = int.Parse((string)(string)model.Element("Id")),
                    Name = (string)model.Element("Name"),
                    SQL = (string)model.Element("SQL")
                }).ToList();
    }

    public ActuatorModel GetById(int id)
    {
        var element = _doc.Descendants("ActuatorModel")
                          .FirstOrDefault(e => (string)e.Element("Id") == id.ToString());
        return element == null ? null : new ActuatorModel
        {
            Id = int.Parse((string)element.Element("Id")),
            Name = (string)element.Element("Name"),
            SQL = (string)element.Element("SQL")
        };
    }

    public void Add(ActuatorModel model)
    {
        var element = new XElement("ActuatorModel",
            new XElement("Id", model.Id),
            new XElement("Name", model.Name),
            new XElement("SQL", model.SQL)
        );
        _doc.Root?.Add(element);
        Save();
    }

    public void Update(ActuatorModel model)
    {
        var element = _doc.Descendants("ActuatorModel")
                          .FirstOrDefault(e => int.Parse((string)e.Element("Id")) == model.Id);
        if (element != null)
        {
            element.SetElementValue("Name", model.Name);
            element.SetElementValue("SQL", model.SQL);
            Save();
        }
    }

    public void Delete(int id)
    {
        var element = _doc.Descendants("ActuatorModel")
                          .FirstOrDefault(e => (string)e.Element("Id") == id.ToString());
        element?.Remove();
        Save();
    }

    public string GetSeriesConfig(int id)
    {
        throw new NotImplementedException();
    }

    private void Save()
    {
        _doc.Save(_filePath);
    }
}